package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.view.View;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.bean.SerializedZQApplyFileList;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.net.BaseResponse;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.widget.PublicLoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TempSavePresenter {

    private WeakReference<ZQApplyView> viewInterfaceWr;
    private WeakReference<ShapeLoadingDialog> dialogWr;
    private String mProjectId;
    private String mCreditorId;
    private int mType;
    private String mCreditorRightsId;
    private ZQBaseProjectCrDecInfo mEditInfo;
    private SerializedZQApplyFileList mSerializedZQApplyFileLists;

    public TempSavePresenter(ZQApplyView viewInterface,
                             ShapeLoadingDialog dialog, String mProjectId, String mCreditorId, int mType, String mCreditorRightsId,
                             ZQBaseProjectCrDecInfo mEditInfo, SerializedZQApplyFileList serializedZQApplyFileLists) {
        this.viewInterfaceWr = new WeakReference<>(viewInterface);
        this.dialogWr = new WeakReference<>(dialog);
        this.mProjectId = mProjectId;
        this.mCreditorId = mCreditorId;
        this.mCreditorRightsId = mCreditorRightsId;
        this.mType = mType;
        this.mEditInfo = mEditInfo;
        this.mSerializedZQApplyFileLists = serializedZQApplyFileLists;
    }

    public void tempSave() {
        ZQApplyView viewInterface = viewInterfaceWr.get();
        if (viewInterface != null) {
            new android.support.v7.app.AlertDialog.Builder(viewInterface.getContext())
                    .setTitle("提示")
                    .setMessage("暂存编辑？")
                    .setCancelable(false)
                    .setPositiveButton("是", (dialogInterface, i) -> {
                        tempSave(false);
                        viewInterface.finish();
                    })
                    .setNegativeButton("否", (dialogInterface, i) -> viewInterface.finish())
                    .show();
        }
    }

    private PublicNoticeDialog publicLoginNoticeDialog;

    private void tempSave(boolean closeActivity) {
        ShapeLoadingDialog mShapeLoadingDialog = dialogWr.get();
        ZQApplyView viewInterface = viewInterfaceWr.get();
        if (viewInterface == null || mShapeLoadingDialog == null) return;

        mShapeLoadingDialog.setLoadingText("保存信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
        viewInterface.syncEdit();
        String strHasEffectiveJudgment = "2";
        String strHasApplyExecution = "2";
        if (mEditInfo.getHasEffectiveJudgment() != null) {
            strHasEffectiveJudgment = mEditInfo.getHasEffectiveJudgment().getValue();
        }
        if (mEditInfo.getHasApplyExecution() != null) {
            strHasApplyExecution = mEditInfo.getHasApplyExecution().getValue();
        }




        Network.getAPIService().saveZQApplyDraft(viewInterface.getUserToken(),
                mProjectId,
                mType,
                mCreditorId,
                0, //状态0--暂存、1--提交，
                mCreditorRightsId,
                mEditInfo.getDeclareAmountPrincipal(),
                mEditInfo.getDeclareAmountInterest(),
                mEditInfo.getDeclareAmountInterestDetail(),
                mEditInfo.getDeclareAmountOther(),
                mEditInfo.getDeclareAmountOtherDetail(),
                mEditInfo.getDeclareAmountRegularTax(),
                mEditInfo.getDeclareAmountOverdueFine(),
                mEditInfo.getDeclareAmountTotal(),
                mEditInfo.getPreferredCreditorRights(),
                mEditInfo.getGuaranteePriority(),
                mEditInfo.getOtherPriority(),
                mEditInfo.getPreferredCreditorRightsDetail(),
                mEditInfo.getCreditorRightsNote(),
                Integer.parseInt(strHasEffectiveJudgment),
                mSerializedZQApplyFileLists.getHasEffectiveJudgmentJson(),
                Integer.parseInt(strHasApplyExecution),
                mSerializedZQApplyFileLists.getHasApplyExecutionJson(),
                mSerializedZQApplyFileLists.getHasOtherDeclarationFileJson(),
                mEditInfo.getExecutiveDetail(),
                mEditInfo.getBank(),
                mEditInfo.getBankBranch(),
                mEditInfo.getBankAccountName(),
                mEditInfo.getBankAccount())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {
                        mShapeLoadingDialog.dismiss();
                        if (response.getCode() == 0) {
                            super.onNext(response);
                            Toast.makeText(viewInterface.getContext(), "已保存", Toast.LENGTH_SHORT).show();
                            if (closeActivity) viewInterface.finish();
//                            publicLoginNoticeDialog = new PublicNoticeDialog(BankruptcyApp.activityRef, new View.OnClickListener() {
//                                @Override
//                                public void onClick( View view ) {
//
//                                    if (view.getId() == R.id.btn_chancel_notice) {//暂存
//
//                                    } else if (view.getId() == R.id.ll_close) {
//
//                                        return;
//                                    } else {//生成
//
//                                    }
//                                    if (closeActivity) viewInterface.finish();
////                                    RegisterActivity.start(BankruptcyApp.activityRef);
//                                    publicLoginNoticeDialog.dismiss();
//
//
//                                }
//                            }, 5, "提示", "您的债权申报已提交成功，管理人将会根据申报信息出具审查意见并通过系统发给您，请注意查看", "取消", "确定");
//                            //更新UI
////                                Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
//                            publicLoginNoticeDialog.show();

                        } else {
                            Toast.makeText(viewInterface.getContext(), response.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        Toast.makeText(viewInterface.getContext(), "保存失败", Toast.LENGTH_SHORT).show();
                        super.onError(e);
                    }
                });
    }

    public void onBackPressed() {
        ZQApplyView viewInterface = viewInterfaceWr.get();
        if (viewInterface != null) {
            new android.support.v7.app.AlertDialog.Builder(viewInterface.getContext())
                    .setTitle("提示")
                    .setMessage("暂存编辑？")
                    .setCancelable(false)
                    .setPositiveButton("是", (dialogInterface, i) -> {
                        tempSave(true);
                        viewInterface.finish();
                    })
                    .setNegativeButton("否", (dialogInterface, i) -> viewInterface.finish())
                    .show();
        }
    }

    public void submit() {
        ShapeLoadingDialog mShapeLoadingDialog = dialogWr.get();
        ZQApplyView viewInterface = viewInterfaceWr.get();
        if (viewInterface == null || mShapeLoadingDialog == null) return;
        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
        viewInterface.syncEdit();

        Network.getAPIService().saveZQApplyDraft(viewInterface.getUserToken(),
                mProjectId,
                mType,
                mCreditorId,
                1, //状态0--暂存、1--提交，
                mCreditorRightsId,
                mEditInfo.getDeclareAmountPrincipal(),
                mEditInfo.getDeclareAmountInterest(),
                mEditInfo.getDeclareAmountInterestDetail(),
                mEditInfo.getDeclareAmountOther(),
                mEditInfo.getDeclareAmountOtherDetail(),
                mEditInfo.getDeclareAmountRegularTax(),
                mEditInfo.getDeclareAmountOverdueFine(),
                mEditInfo.getDeclareAmountTotal(),
                mEditInfo.getPreferredCreditorRights(),
                mEditInfo.getGuaranteePriority(),
                mEditInfo.getOtherPriority(),
                mEditInfo.getPreferredCreditorRightsDetail(),
                mEditInfo.getCreditorRightsNote(),
                Integer.parseInt(mEditInfo.getHasEffectiveJudgment().getValue()),
                mSerializedZQApplyFileLists.getHasEffectiveJudgmentJson(),
                Integer.parseInt(mEditInfo.getHasApplyExecution().getValue()),
                mSerializedZQApplyFileLists.getHasApplyExecutionJson(),
                mSerializedZQApplyFileLists.getHasOtherDeclarationFileJson(),
                mEditInfo.getExecutiveDetail(),
                mEditInfo.getBank(),
                mEditInfo.getBankBranch(),
                mEditInfo.getBankAccountName(),
                mEditInfo.getBankAccount())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {
                        mShapeLoadingDialog.dismiss();
                        if (response.getCode() == 0) {
                            super.onNext(response);
//                            Toast.makeText(viewInterface.getContext(), "已提交", Toast.LENGTH_SHORT).show();
//                            viewInterface.finish();


                            if(mType == 0)
                            {
                                Toast.makeText(viewInterface.getContext(), "提交成功", Toast.LENGTH_SHORT).show();
                                viewInterface.finish();
                                return;
                            }

                            Toast.makeText(viewInterface.getContext(), "您的债权申报已提交成功", Toast.LENGTH_SHORT).show();
                            viewInterface.finish();
                            return;
//                                publicLoginNoticeDialog = new PublicNoticeDialog(BankruptcyApp.activityRef, new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//
//                                        if (view.getId() == R.id.btn_chancel_notice) {//暂存
//
//                                        } else if (view.getId() == R.id.ll_close) {
//                                            viewInterface.finish();
//                                            return;
//                                        } else {//生成
//
//                                        }
//                                        viewInterface.finish();
////                                    RegisterActivity.start(BankruptcyApp.activityRef);
//                                        publicLoginNoticeDialog.dismiss();
//
//
//                                    }
//                                }, 5, "提示", "您的债权申报已提交成功，管理人将会根据申报信息出具审查意见并通过系统发给您，请注意查看", "取消", "确定");
////                            }
//                            //更新UI
////                                Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
//                            publicLoginNoticeDialog.show();
                        } else {
                            Toast.makeText(viewInterface.getContext(), response.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        Toast.makeText(viewInterface.getContext(), "提交失败", Toast.LENGTH_SHORT).show();
                        super.onError(e);
                    }
                });
    }
}
